import { prisma } from '@/config/database'

export const albumsService = {
  async listAlbums(userId: string, partnerId?: string | null) {
    const ownerIds = partnerId ? { in: [userId, partnerId] } : userId
    return prisma.album.findMany({
      where: { userId: ownerIds as any },
      orderBy: { createdAt: 'desc' },
    })
  },

  async createAlbum(userId: string, title: string, coverUrl?: string) {
    return prisma.album.create({
      data: { userId, title, coverUrl },
    })
  },

  async updateAlbum(userId: string, albumId: string, data: { title?: string; coverUrl?: string }) {
    // 限制只能修改自己的相册
    const album = await prisma.album.findFirst({ where: { id: albumId, userId } })
    if (!album) throw new Error('相册不存在或无权限')
    return prisma.album.update({
      where: { id: albumId },
      data,
    })
  },

  async deleteAlbum(userId: string, albumId: string) {
    const album = await prisma.album.findFirst({ where: { id: albumId, userId } })
    if (!album) throw new Error('相册不存在或无权限')
    await prisma.photo.deleteMany({ where: { albumId } })
    await prisma.album.delete({ where: { id: albumId } })
    return { success: true }
  },

  async listPhotos(userId: string, partnerId: string | null | undefined, albumId: string) {
    // 允许查看“我+伙伴”的相册照片
    const album = await prisma.album.findFirst({
      where: partnerId
        ? { id: albumId, userId: { in: [userId, partnerId] as any } }
        : { id: albumId, userId },
      select: { id: true },
    })
    if (!album) throw new Error('相册不存在或无权限')
    return prisma.photo.findMany({
      where: { albumId },
      orderBy: { createdAt: 'desc' },
    })
  },

  async addPhoto(userId: string, partnerId: string | null | undefined, params: {
    albumId: string
    url: string
    mime: string
    size: number
    title?: string
    description?: string
    width?: number
    height?: number
    tags?: string[]
  }) {
    // 允许向“我+伙伴”的相册添加
    const album = await prisma.album.findFirst({
      where: partnerId
        ? { id: params.albumId, userId: { in: [userId, partnerId] as any } }
        : { id: params.albumId, userId },
      select: { id: true, userId: true },
    })
    if (!album) throw new Error('相册不存在或无权限')

    return prisma.photo.create({
      data: {
        albumId: params.albumId,
        userId, // 上传者
        url: params.url,
        mime: params.mime,
        size: params.size,
        title: params.title,
        description: params.description,
        width: params.width,
        height: params.height,
        tags: params.tags || [],
      },
    })
  },

  async deletePhoto(userId: string, photoId: string) {
    // 仅允许删除自己上传的照片（或可放宽：相册拥有者可删）
    const photo = await prisma.photo.findFirst({ where: { id: photoId, userId } })
    if (!photo) throw new Error('照片不存在或无权限')
    await prisma.photo.delete({ where: { id: photoId } })
    return { success: true }
  },

  async toggleLike(userId: string, photoId: string) {
    // 简化：任何在共享范围内看到的照片都可点赞（不限制上传者）
    const photo = await prisma.photo.findFirst({ where: { id: photoId } })
    if (!photo) throw new Error('照片不存在')
    return prisma.photo.update({
      where: { id: photoId },
      data: { liked: !photo.liked },
    })
  },
}